package config

import (
	"fmt"
	"time"

	"github.com/spf13/viper"
)

// Config 全局配置
type Config struct {
	App        AppConfig        `mapstructure:"app"`
	Database   DatabaseConfig   `mapstructure:"database"`
	JWT        JWTConfig        `mapstructure:"jwt"`
	Log        LogConfig        `mapstructure:"log"`
	CORS       CORSConfig       `mapstructure:"cors"`
	RateLimit  RateLimitConfig  `mapstructure:"ratelimit"`
	Upload     UploadConfig     `mapstructure:"upload"`
	Password   PasswordConfig   `mapstructure:"password"`
	Pagination PaginationConfig `mapstructure:"pagination"`
	Swagger    SwaggerConfig    `mapstructure:"swagger"`
}

// AppConfig 应用配置
type AppConfig struct {
	Name    string `mapstructure:"name"`
	Version string `mapstructure:"version"`
	Mode    string `mapstructure:"mode"`
	Port    int    `mapstructure:"port"`
	Host    string `mapstructure:"host"`
}

// DatabaseConfig 数据库配置
type DatabaseConfig struct {
	MySQL MySQLConfig `mapstructure:"mysql"`
	Redis RedisConfig `mapstructure:"redis"`
}

// MySQLConfig MySQL 配置
type MySQLConfig struct {
	Host            string `mapstructure:"host"`
	Port            int    `mapstructure:"port"`
	Username        string `mapstructure:"username"`
	Password        string `mapstructure:"password"`
	DBName          string `mapstructure:"dbname"`
	Charset         string `mapstructure:"charset"`
	ParseTime       bool   `mapstructure:"parseTime"`
	Loc             string `mapstructure:"loc"`
	MaxIdleConns    int    `mapstructure:"maxIdleConns"`
	MaxOpenConns    int    `mapstructure:"maxOpenConns"`
	ConnMaxLifetime int    `mapstructure:"connMaxLifetime"`
	LogLevel        int    `mapstructure:"logLevel"`
}

// RedisConfig Redis 配置
type RedisConfig struct {
	Host         string `mapstructure:"host"`
	Port         int    `mapstructure:"port"`
	Password     string `mapstructure:"password"`
	DB           int    `mapstructure:"db"`
	PoolSize     int    `mapstructure:"poolSize"`
	MinIdleConns int    `mapstructure:"minIdleConns"`
	MaxRetries   int    `mapstructure:"maxRetries"`
}

// JWTConfig JWT 配置
type JWTConfig struct {
	Secret           string `mapstructure:"secret"`
	Issuer           string `mapstructure:"issuer"`
	ExpiresIn        int    `mapstructure:"expiresIn"`
	RefreshExpiresIn int    `mapstructure:"refreshExpiresIn"`
}

// LogConfig 日志配置
type LogConfig struct {
	Level      string `mapstructure:"level"`
	Format     string `mapstructure:"format"`
	Output     string `mapstructure:"output"`
	Filename   string `mapstructure:"filename"`
	MaxSize    int    `mapstructure:"maxSize"`
	MaxBackups int    `mapstructure:"maxBackups"`
	MaxAge     int    `mapstructure:"maxAge"`
	Compress   bool   `mapstructure:"compress"`
}

// CORSConfig CORS 配置
type CORSConfig struct {
	AllowOrigins     []string `mapstructure:"allowOrigins"`
	AllowMethods     []string `mapstructure:"allowMethods"`
	AllowHeaders     []string `mapstructure:"allowHeaders"`
	ExposeHeaders    []string `mapstructure:"exposeHeaders"`
	AllowCredentials bool     `mapstructure:"allowCredentials"`
	MaxAge           int      `mapstructure:"maxAge"`
}

// RateLimitConfig 限流配置
type RateLimitConfig struct {
	Enabled bool `mapstructure:"enabled"`
	Rate    int  `mapstructure:"rate"`
	Burst   int  `mapstructure:"burst"`
}

// UploadConfig 文件上传配置
type UploadConfig struct {
	MaxSize      int64    `mapstructure:"maxSize"`
	AllowedTypes []string `mapstructure:"allowedTypes"`
	SavePath     string   `mapstructure:"savePath"`
}

// PasswordConfig 密码配置
type PasswordConfig struct {
	BcryptCost      int `mapstructure:"bcryptCost"`
	MinLength       int `mapstructure:"minLength"`
	MaxFailAttempts int `mapstructure:"maxFailAttempts"`
	LockDuration    int `mapstructure:"lockDuration"`
}

// PaginationConfig 分页配置
type PaginationConfig struct {
	DefaultPage     int `mapstructure:"defaultPage"`
	DefaultPageSize int `mapstructure:"defaultPageSize"`
	MaxPageSize     int `mapstructure:"maxPageSize"`
}

// SwaggerConfig Swagger 配置
type SwaggerConfig struct {
	Enabled     bool   `mapstructure:"enabled"`
	Title       string `mapstructure:"title"`
	Description string `mapstructure:"description"`
	Version     string `mapstructure:"version"`
	Host        string `mapstructure:"host"`
	BasePath    string `mapstructure:"basePath"`
}

// GlobalConfig 全局配置实例
var GlobalConfig *Config

// LoadConfig 加载配置文件
func LoadConfig() error {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./config")
	viper.AddConfigPath("../config")
	viper.AddConfigPath(".")

	// 读取环境变量
	viper.AutomaticEnv()

	if err := viper.ReadInConfig(); err != nil {
		return fmt.Errorf("读取配置文件失败: %w", err)
	}

	GlobalConfig = &Config{}
	if err := viper.Unmarshal(GlobalConfig); err != nil {
		return fmt.Errorf("解析配置文件失败: %w", err)
	}

	return nil
}

// GetJWTExpiresIn 获取 JWT 过期时间
func GetJWTExpiresIn() time.Duration {
	return time.Duration(GlobalConfig.JWT.ExpiresIn) * time.Second
}

// GetRefreshTokenExpiresIn 获取刷新令牌过期时间
func GetRefreshTokenExpiresIn() time.Duration {
	return time.Duration(GlobalConfig.JWT.RefreshExpiresIn) * time.Second
}

// GetPasswordLockDuration 获取密码锁定时长
func GetPasswordLockDuration() time.Duration {
	return time.Duration(GlobalConfig.Password.LockDuration) * time.Second
}

// GetMySQLDSN 获取 MySQL DSN
func GetMySQLDSN() string {
	c := GlobalConfig.Database.MySQL
	
	// 使用简化的DSN格式，适用于开发环境
	if c.Password == "" {
		// 无密码连接
		return fmt.Sprintf("%s@tcp(%s:%d)/%s?charset=%s&parseTime=%t&loc=Local",
			c.Username,
			c.Host,
			c.Port,
			c.DBName,
			c.Charset,
			c.ParseTime,
		)
	} else {
		// 有密码连接
		return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=%t&loc=Local",
			c.Username,
			c.Password,
			c.Host,
			c.Port,
			c.DBName,
			c.Charset,
			c.ParseTime,
		)
	}
}

// GetRedisAddr 获取 Redis 地址
func GetRedisAddr() string {
	c := GlobalConfig.Database.Redis
	return fmt.Sprintf("%s:%d", c.Host, c.Port)
}
